package com.qidian.mes.pro.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qidian.mes.pojo.WorkTicket;
import com.qidian.mes.pro.mapper.WorkTicketMapper;
import com.qidian.mes.pro.service.WorkTicketService;
import com.qidian.mes.util.pojo.MESResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author chenzheng
 * @Company 起点编程
 * @Time 2023/10/26 16:19
 * @Description
 */
@Service
public class WorkTicketServiceImpl implements WorkTicketService {
    //注意WorkTicket中的id为workorderId
    @Autowired
    private WorkTicketMapper workTicketMapper;
    @Override
    public MESResult queryById(Long workorderId) {
        WorkTicket workTicket = null;
        if ((workTicket = workTicketMapper.selectById(workorderId)) != null){
            return MESResult.ok(workTicket);
        }
        return MESResult.empty();
    }

    @Override
    public MESResult save(WorkTicket workTicket) {
        // 校验用户名是否重复
        if(workTicket.getWorkorderName() != null && workTicketMapper.selectByWorkorderName(workTicket.getWorkorderName()) != null){
            return MESResult.duplicate("用户名重复");
        }
        // updateIsOk会根据传入的参数判断返回的结果
        return MESResult.updateIsOk(workTicketMapper.save(workTicket));
    }

    @Override
    public MESResult update(WorkTicket workTicket) {
        // 校验是否重复
        WorkTicket workTicket1 = workTicketMapper.selectByWorkorderName(workTicket.getWorkorderName());
        if(workTicket1 != null && !workTicket1.getWorkorderId().equals(workTicket.getWorkorderId())){
            return MESResult.duplicate("用户名重复");
        }
        return MESResult.updateIsOk(workTicketMapper.update(workTicket));
    }

    @Override
    public MESResult delete(Long workorderId) {
        return MESResult.updateIsOk(workTicketMapper.delete(workorderId));
    }
    @Override
    public MESResult list(int page, int limit, WorkTicket workTicket) {
// 开启分页 在当前线程中执行下一条SQL的时候就会进行分页。
        PageHelper.startPage(page,limit);
        List<WorkTicket> list = workTicketMapper.list(workTicket);
// 组织一个分页对象。（页码，每页大小，最大页码，数据，总条数）
        PageInfo<WorkTicket> pageInfo = new PageInfo<>(list);
        return MESResult.ok(pageInfo);
    }
}
